<?php
//include 'WechatBase.php'
//不引用也会自动加载
//微信模板消息接口
class WechatMessageHelper extends WechatBase{
	
	public function get_access_token(){
		$access_token = '';
		$data = $this->readArr('access_token');
		if(
			!empty($data['access_token']) && 
			!empty($data['expires'])
		){
			if($data['expires'] > time()){
				return $data['access_token'];
			}
		}
		
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
		$url.= "&appid={$this->Appid}&secret=" . $this->Secret;
		$response = \HttpHelper::get($url);
		$data = json_decode($response,true);
		if(
			isset($data['access_token']) && 
			isset($data['expires_in'])
		){
			$access_token = $data['access_token'];
			$newdata = [
				'access_token' => $access_token,
				'expires' => time() + 7000
			];
			$this->writeArr('access_token',$newdata);
		}
		return $access_token;
	}
  
    private function sendData($access_token,$data){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
        if(is_array($data)){
            $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        }
        $html = \HttpHelper::post($url,$data);
        return $html;
    }
    
    public function sendMsg($message_data){
		
		$testdata = [
			'touser' => 'openid',
			'template_id' => '消息模板ID',
			'url' => '点击详情的跳转网址，可空',
			'data' => [
				'frist' => [
					'value' => 'neirong',
					'color' => '#173177',
				],
			]
		];
		
        $access_token = $this->get_access_token();
        $response = $this->sendData($access_token,$message_data);
        return $response;
    }
	
}